﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using System.Net;
using System.Configuration;
using System.Net.Mail;

namespace IpSpy
{
	public partial class IpSpyService : ServiceBase
	{
		private Timer timer;
		private string ipAddress = "";
		private readonly Object myLock = new Object();

		public IpSpyService()
		{
			InitializeComponent();

			int checkInterval = Convert.ToInt32(ConfigurationManager.AppSettings["CheckInterval"]);
			timer = new Timer(new TimerCallback(timerCallback), null, new TimeSpan(0, 0, 5), TimeSpan.FromMinutes(checkInterval));
		}

		protected override void OnStart(string[] args)
		{
			LogManager.Log("IPSpy Started");
		}

		protected override void OnStop()
		{
			LogManager.Log("IPSpy Stopped");
		}

		private void timerCallback(object state)
		{
			Thread t = new Thread(new ThreadStart(checkIP));
			t.Start();
		}

		private void checkIP()
		{
			try
			{
				Thread t = new Thread(new ThreadStart(checkIP));
				WebClient cl = new WebClient();
				string newIP = cl.DownloadString(ConfigurationManager.AppSettings["IPProviderHost"]);

				lock (ipAddress)
				{
					if (ipAddress != newIP)
					{
						LogManager.Log("IP changed to " + newIP + ", sending mail..");
						SendMail(newIP);
						ipAddress = newIP;
					}
				}
			}
			catch (Exception ex)
			{
				WriteLog(ex.Message, EventLogEntryType.Error);
				LogManager.Log(ex.Message + ": " + ex.StackTrace);
			}
		}

		private void SendMail(string ip)
		{
			try
			{
				System.Net.NetworkCredential credential =
					new System.Net.NetworkCredential(
						ConfigurationManager.AppSettings["SMTP.Login"],
						ConfigurationManager.AppSettings["SMTP.Password"]);

				System.Net.Mail.MailMessage message = new MailMessage();
				message.To.Add(ConfigurationManager.AppSettings["Email.To"]);
				message.Subject = ConfigurationManager.AppSettings["Email.Subject"];

				message.From = new System.Net.Mail.MailAddress(ConfigurationManager.AppSettings["SMTP.Login"]);
				message.Body = String.Format(ConfigurationManager.AppSettings["Email.BodyFormat"], ip);

				System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient(ConfigurationManager.AppSettings["SMTP.Host"]);
				smtpClient.UseDefaultCredentials = false;
				smtpClient.EnableSsl = Convert.ToBoolean(ConfigurationManager.AppSettings["SMTP.EnableSSL"]);
				smtpClient.Credentials = credential;
				smtpClient.Port = 587;
				smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
				smtpClient.Send(message);
				LogManager.Log("Mail sent to " + message.To[0].Address);
			}
			catch (Exception ex)
			{
				WriteLog(ex.Message, EventLogEntryType.Error);
				LogManager.Log(ex.Message + ": " + ex.StackTrace);
			}
		}

		private void WriteLog(string s, EventLogEntryType e)
		{
			try
			{
				string sSource = "IpSpy";
				string sLog = "Application";

				if (!EventLog.SourceExists(sSource))
					EventLog.CreateEventSource(sSource, sLog);

				EventLog.WriteEntry(sSource, s, EventLogEntryType.Warning);
			}
			catch (Exception ex)
			{
				LogManager.Log(ex.Message + ": " + ex.StackTrace); 
			}
		}
	}
}
